// generate 3 server to handle request for test

package main

import (
	"fmt"
	"net/http"
	"sync"
)

type testServer struct {
	addr         string
	requestCount int
	lock         *sync.Mutex
}

func (server *testServer) handler(res http.ResponseWriter, req *http.Request) {
	server.lock.Lock()
	server.requestCount += 1
	server.lock.Unlock()
	fmt.Printf("%s: %s %s on serverHandlerPort: %s, Total: %d\n",
		req.Proto, req.Method, req.RequestURI, server.addr, server.requestCount)
	_, _ = res.Write([]byte(server.addr))
}

func main() {
	nodeA := testServer{"127.0.0.1:7791", 0, new(sync.Mutex)}
	nodeB := testServer{"127.0.0.1:7792", 0, new(sync.Mutex)}
	nodeC := testServer{"127.0.0.1:7793", 0, new(sync.Mutex)}

	nodes := []testServer{nodeA, nodeB, nodeC}

	serverA := http.NewServeMux()
	serverA.HandleFunc("/", nodeA.handler)
	go http.ListenAndServe(nodeA.addr, serverA)

	serverB := http.NewServeMux()
	serverB.HandleFunc("/", nodeB.handler)
	go http.ListenAndServe(nodeB.addr, serverB)

	serverC := http.NewServeMux()
	serverC.HandleFunc("/", nodeC.handler)
	go http.ListenAndServe(nodeC.addr, serverC)

	var comm int

	for _, node := range nodes {
		fmt.Printf("Server %s started...\n", node.addr)
	}

	fmt.Println("All server are started, input any key and enter to quit...")
	_, _ = fmt.Scan(&comm)
	fmt.Printf("Result: ServerA: %d  ServerB: %d  ServerC: %d  Total: %d \n",
		nodeA.requestCount, nodeB.requestCount, nodeC.requestCount, nodeA.requestCount + nodeB.requestCount + nodeC.requestCount)
}
